package com.youlai.boot.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.common.constant.SystemConstants;
import com.youlai.boot.core.security.util.SecurityUtils;
import com.youlai.boot.system.converter.PlateConverter;
import com.youlai.boot.system.mapper.PlateMapper;
import com.youlai.boot.system.model.entity.Plate;
import com.youlai.boot.system.model.event.query.PlatePageQuery;
import com.youlai.boot.system.model.vo.PlatePageVO;
import com.youlai.boot.system.service.PlateService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * 板材业务实现类
 *
 * @author haoxr
 * @since 2022/6/3
 */
@Service
@RequiredArgsConstructor
public class PlateServiceImpl extends ServiceImpl<PlateMapper, Plate> implements PlateService {
    private final PlateConverter plateConverter;
    /**
     * 板材分页列表
     *
     * @param queryParams 板材查询参数
     * @return {@link Page <  PlatePageVO  >} – 板材分页列表
     */
    @Override
    public Page<PlatePageVO> getPlatePage(PlatePageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();

        // 查询数据
        Page<Plate> platePage = this.page(new Page<>(pageNum, pageSize),
                new LambdaQueryWrapper<Plate>()
                        .and(StrUtil.isNotBlank(keywords),
                                wrapper ->
                                        wrapper.like(Plate::getName, keywords)
                                                .or()
                                                .like(Plate::getCode, keywords)
                        )
                        .ne(!SecurityUtils.isRoot(), Plate::getCode, SystemConstants.ROOT_ROLE_CODE) // 非超级管理员不显示超级管理员板材
                        .orderByAsc(Plate::getSort).orderByDesc(Plate::getCreateTime).orderByDesc(Plate::getUpdateTime)
        );
        // 实体转换
        return plateConverter.toPageVo(platePage);
    }
    
    /**
     * 获取最大范围的数据权限
     *
     * @param plates 板材编码集合
     * @return {@link Integer} – 数据权限范围
     */
    @Override
    public Integer getMaximumDataScope(Set<String> plates) {
        Integer dataScope = this.baseMapper.getMaximumDataScope(plates);
        return dataScope;
    }
}
